const router = require('koa-router')();
const { prize } = require("../omodels/prize");
const Joi = require('joi');
const validationMiddleware = require('../middleware/validate');
const response = require("../utils/response");
const { dealNotEmpty } = require("../utils/dberrordeal");

const rulesSchema = {
    '/addPrize': Joi.object({
        name: dealNotEmpty('名称'),
        rate: dealNotEmpty('概率'),
        number: dealNotEmpty('金额')
    }),
    '/delPrize': Joi.object({
        id: dealNotEmpty('id')
    })
};

router.get('/prizeList', async (ctx, next) => {
    let res = await prize.find();
    if (res) {
        response.success(ctx, { data: res });
    } else {
        response.error(ctx, {});
    }
});

router.post('/addPrize', validationMiddleware(rulesSchema), async (ctx, next) => {
    let data = ctx.request.body;
    await prize.create(data).then(res => {
        response.success(ctx, {});
    }).catch(err => {
        response.error(ctx, { message: err.toString() || '新增失败' });
    });
});

router.post('/delPrize', validationMiddleware(rulesSchema), async (ctx, next) => {
    let data = ctx.request.body;
    let res = await prize.removePrizeAndAdjustRate(data.id);
    if (res) {
        response.success(ctx, {});
    } else {
        response.error(ctx, {});
    }
});

module.exports = router;
